<?php
namespace app\service;

use think\facade\Db;

class PointsService
{
    /**
     * 获取用户积分余额
     * @param int $userId 用户ID
     * @return int
     */
    public function getUserPoints($userId)
    {
        $user = Db::name('users')->where('id', $userId)->find();
        return $user['points'] ?? 0;
    }

    /**
     * 充值积分
     * @param int $userId 用户ID
     * @param int $points 充值积分数量
     * @param string $orderId 订单ID
     * @param string $description 描述
     * @param int|null $operatorId 操作人ID
     * @throws \Exception
     */
    public function recharge($userId, $points, $orderId, $description = '', $operatorId = null)
    {
        if ($points <= 0) {
            throw new \Exception('充值积分必须大于0');
        }

        Db::startTrans();
        try {
            // 更新用户积分
            $user = Db::name('users')->lock(true)->where('id', $userId)->find();
            if (!$user) {
                throw new \Exception('用户不存在');
            }

            $newBalance = $user['points'] + $points;
            Db::name('users')
                ->where('id', $userId)
                ->update(['points' => $newBalance]);

            // 记录积分变动
            Db::name('points_log')->insert([
                'user_id' => $userId,
                'type' => 'recharge',
                'change' => $points,
                'balance' => $newBalance,
                'remark' => $description,
                'create_time' => time()
            ]);

            Db::commit();
            return $newBalance;
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 消费积分
     * @param int $userId 用户ID
     * @param int $points 消费积分数量
     * @param string $description 描述
     * @param string|null $taskId 任务ID
     * @throws \Exception
     */
    public function consume($userId, $points, $description = '', $taskId = null)
    {
        if ($points <= 0) {
            throw new \Exception('消费积分必须大于0');
        }

        Db::startTrans();
        try {
            // 检查用户积分是否足够
            $user = Db::name('users')->lock(true)->where('id', $userId)->find();
            if (!$user) {
                throw new \Exception('用户不存在');
            }

            if ($user['points'] < $points) {
                throw new \Exception('积分不足');
            }

            $newBalance = $user['points'] - $points;
            
            // 更新用户积分
            Db::name('users')
                ->where('id', $userId)
                ->update(['points' => $newBalance]);

            // 记录积分变动
            Db::name('points_log')->insert([
                'user_id' => $userId,
                'type' => 'consume',
                'change' => -$points, // 消费为负数
                'balance' => $newBalance,
                'remark' => $description,
                'create_time' => time()
            ]);

            Db::commit();
            return $newBalance;
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 获取用户积分明细
     * @param int $userId 用户ID
     * @param int $page 页码
     * @param int $pageSize 每页数量
     * @param string|null $type 类型：recharge/consume/null(全部)
     * @param string|null $startDate 开始日期
     * @param string|null $endDate 结束日期
     * @return array
     */
    public function getPointsLogs($userId, $page = 1, $pageSize = 10, $type = null, $startDate = null, $endDate = null)
    {
        $query = Db::name('points_log')->where('user_id', $userId);

        // 按类型筛选
        if ($type) {
            $query->where('type', $type);
        }

        // 按日期筛选
        if ($startDate) {
            $query->where('create_time', '>=', $startDate . ' 00:00:00');
        }
        if ($endDate) {
            $query->where('create_time', '<=', $endDate . ' 23:59:59');
        }

        // 获取总数
        $total = $query->count();

        // 获取列表
        $list = $query->order('create_time', 'desc')
            ->page($page, $pageSize)
            ->select()
            ->each(function($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });

        // 获取用户当前积分
        $currentPoints = $this->getUserPoints($userId);

        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'page_size' => $pageSize,
            'current_points' => $currentPoints
        ];
    }

    /**
     * 获取用户积分统计
     * @param int $userId 用户ID
     * @param string|null $startDate 开始日期
     * @param string|null $endDate 结束日期
     * @return array
     */
    public function getPointsStats($userId, $startDate = null, $endDate = null)
    {
        $query = Db::name('points_log')->where('user_id', $userId);

        // 按日期筛选
        if ($startDate) {
            $query->where('create_time', '>=', $startDate . ' 00:00:00');
        }
        if ($endDate) {
            $query->where('create_time', '<=', $endDate . ' 23:59:59');
        }

        // 充值统计
        $rechargeStats = $query->where('type', 'recharge')
            ->field('COUNT(*) as count, SUM(points) as total')
            ->find();

        // 消费统计
        $consumeStats = $query->where('type', 'consume')
            ->field('COUNT(*) as count, SUM(points) as total')
            ->find();

        return [
            'recharge' => [
                'count' => $rechargeStats['count'] ?? 0,
                'total' => $rechargeStats['total'] ?? 0
            ],
            'consume' => [
                'count' => $consumeStats['count'] ?? 0,
                'total' => abs($consumeStats['total'] ?? 0) // 转为正数
            ],
            'current_points' => $this->getUserPoints($userId)
        ];
    }
} 